<template>
  <view class="statistics-container">
    <!-- 筛选条件区域 -->
    <view class="filter-section">
      <view class="filter-row">
        <view class="filter-item">
          <text class="filter-label">时间范围</text>
          <picker @change="onTimeTypeChange" :value="timeTypeIndex" :range="timeTypeOptions">
            <view class="picker">{{ timeTypeOptions[timeTypeIndex] }}</view>
          </picker>
        </view>
        
        <view class="filter-item">
          <text class="filter-label">开始时间</text>
          <picker mode="date" @change="onStartDateChange">
            <view class="picker">{{ filterForm.startDate }}</view>
          </picker>
        </view>
        
        <view class="filter-item">
          <text class="filter-label">结束时间</text>
          <picker mode="date" @change="onEndDateChange">
            <view class="picker">{{ filterForm.endDate }}</view>
          </picker>
        </view>
      </view>
      
      <view class="filter-row">
        <view class="filter-item">
          <text class="filter-label">统计维度</text>
          <picker @change="onDimensionChange" :value="dimensionIndex" :range="dimensionOptions">
            <view class="picker">{{ dimensionOptions[dimensionIndex] }}</view>
          </picker>
        </view>
        
        <view class="filter-item" v-if="filterForm.dimension === 'personal'">
          <text class="filter-label">选择人员</text>
          <picker @change="onUserChange" :value="userIndex" :range="userOptions" range-key="nickname">
            <view class="picker">{{ userOptions[userIndex]?userOptions[userIndex]['nickname'] : '请选择' }}</view>
          </picker>
        </view>
        
        <view class="filter-item" v-if="filterForm.dimension === 'department'">
          <text class="filter-label">选择部门</text>
          <picker @change="onDeptChange" :value="deptIndex" :range="deptOptions" range-key="name">
            <view class="picker">{{ deptOptions[deptIndex]?deptOptions[deptIndex]['name'] : '请选择' }}</view>
          </picker>
        </view>
        
        <view class="filter-item" v-if="filterForm.dimension === 'multi-department'">
          <text class="filter-label">选择多部门</text>
          <view class="multi-picker" @click="showMultiDept = true">
            <text>{{ getMultiDeptText() }}</text>
          </view>
        </view>
		<view class="filter-item">
			<text class="filter-label">点击查询</text>
		   <button class="query-btn" @click="handleQuery" :loading="loading">查询</button>
		</view>
      </view>
      
     
    </view>

    <!-- 多部门选择弹窗 -->
    <uni-popup ref="multiDeptPopup" type="bottom">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">选择部门</text>
          <text class="popup-close" @click="showMultiDept = false">完成</text>
        </view>
        <scroll-view class="popup-list" scroll-y>
          <view class="popup-item" v-for="dept in deptOptions" :key="dept._id">
            <checkbox :value="dept._id" :checked="filterForm.multiDepts.includes(dept._id)" 
                     @click="toggleDept(dept._id)" />
            <text class="dept-name">{{ dept ? dept.name : '-' }}</text>
          </view>
        </scroll-view>
      </view>
    </uni-popup>

    <!-- 统计概览 -->
    <view class="overview-section">
      <view class="overview-card">
        <text class="overview-value">{{ statistics.totalDeals }}</text>
        <text class="overview-label">总成交数</text>
      </view>
      <view class="overview-card">
        <text class="overview-value">{{ statistics.totalAmount }}万</text>
        <text class="overview-label">总成交金额</text>
      </view>
      <view class="overview-card">
        <text class="overview-value">{{ statistics.totalServiceFee }}万</text>
        <text class="overview-label">总服务费</text>
      </view>
      <view class="overview-card">
        <text class="overview-value">{{ statistics.avgAmount }}万</text>
        <text class="overview-label">平均成交额</text>
      </view>
    </view>

    <!-- 图表区域 -->
    <view class="chart-section">
      <view class="chart-tabs">
        <text class="chart-tab" :class="{active: activeChart === 'trend'}" 
              @click="activeChart = 'trend'">趋势图</text>
        <text class="chart-tab" :class="{active: activeChart === 'product'}" 
              @click="activeChart = 'product'">产品分布</text>
        <text class="chart-tab" :class="{active: activeChart === 'department'}" 
              @click="activeChart = 'department'">部门分布</text>
      </view>
      
      <view class="chart-container">
		<view class="uni-charts-box">
			<charts1 v-if="activeChart == 'trend'"></charts1>
			<charts2 v-if="activeChart == 'product'"></charts2>
			<charts3 v-if="activeChart == 'department'"></charts3>
		</view>
      </view>
    </view>

    <!-- 数据表格 -->
    <view class="table-section">
      <view class="table-header">
        <text class="table-title">成交明细</text>
		<download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcelData" :type="exportExcel.type" :name="exportExcel.filename">
		  <button class="uni-button" type="primary" size="mini">导出 Excel</button>
		</download-excel>
      </view>
      
      <scroll-view class="table-container" scroll-x>
        <view class="table">
          <view class="table-row header-row">
            <text class="table-cell">成交时间</text>
            <text class="table-cell">客户姓名</text>
            <text class="table-cell">成交部门</text>
            <text class="table-cell">成交人员</text>
            <text class="table-cell">成交产品</text>
            <text class="table-cell">成交类型</text>
            <text class="table-cell">成交金额(万)</text>
            <text class="table-cell">服务费(万)</text>
          </view>
          
          <view class="table-row" v-for="item in tableData" :key="item.id">
            <text class="table-cell"><uni-dateformat :threshold="[0, 0]" :date="item.dealTime"></uni-dateformat></text>
            <text class="table-cell">{{ item.customerName }}</text>
            <text class="table-cell">{{ item.dealDepartment }}</text>
            <text class="table-cell">{{ item.dealPerson }}</text>
            <text class="table-cell">{{ item.product }}</text>
            <text class="table-cell">{{ item.dealType }}</text>
            <text class="table-cell">{{ item.amount }}</text>
            <text class="table-cell">{{ item.serviceFee }}</text>
          </view>
        </view>
      </scroll-view>
      
      <!-- 分页 -->
      <view class="pagination" v-if="tableData.length > 0">
        <text class="pagination-text">
          共 {{ total }} 条记录，第 {{ currentPage }}/{{ Math.ceil(total / pageSize) }} 页
        </text>
        <view class="pagination-btns">
          <button class="page-btn" @click="handlePrevPage" :disabled="currentPage === 1">上一页</button>
          <button class="page-btn" @click="handleNextPage" :disabled="currentPage * pageSize >= total">下一页</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import charts1 from './charts1.vue'
import charts2 from './charts2.vue'
import charts3 from './charts3.vue'
export default {
  components:{charts1,charts2,charts3},
  data() {
    return {
      loading: false,
      // 筛选表单
      filterForm: {
        timeType: 'day',
        startDate: this.getDefaultDate(-7),
        endDate: this.getDefaultDate(0),
        dimension: 'personal',
        userId: '',
        deptId: '',
        multiDepts: []
      },
      // 选项数据
      timeTypeIndex: 0,
      timeTypeOptions: ['按日', '按周', '按月', '按年'],
      dimensionIndex: 0,
      dimensionOptions: ['个人', '部门'],
      userIndex: 0,
      userOptions: [],
      deptIndex: 0,
      deptOptions: [],
      // 多部门选择
      showMultiDept: false,
      // 统计概览数据
      statistics: {
        totalDeals: 0,
        totalAmount: 0,
        totalServiceFee: 0,
        avgAmount: 0
      },
	  // 
	  activeChart:'trend',
      // 表格数据
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
	  exportExcel: {
	    "filename": "成交记录.xls",
	    "type": "xls",
	    "fields": {
	      "成交时间": "dealTime",
	      "客户姓名": "customerName",
	      "成交部门": "dealDepartment",
	      "成交人员": "dealPerson",
	      "成交产品": "product",
	      "成交类型": "dealType",
	      "成交金额": "amount",
	      "服务费": "serviceFee"
	    }
	  },
	  exportExcelData: []
    }
  },
  
  onLoad() {
    this.initData()
    this.loadStatistics()
  },
  // 监听图表类型变化
  watch: {
    activeChart: {
      handler(newVal) {
        if (this.tableData.length > 0) {
          this.loadChartData()
        }
      },
      immediate: false
    }
  },
  methods: {
    // 初始化数据
    initData() {
      this.loadUsers()
      this.loadDepartments()
    },
    
    // 获取默认日期
    getDefaultDate(offset = 0) {
      const date = new Date()
      date.setDate(date.getDate() + offset)
      return date.toISOString().split('T')[0]
    },
    
    // 加载用户列表
    async loadUsers() {
      try {
        const res = await uniCloud.database().collection('uni-id-users').field('name,nickname').get()
        this.userOptions = res.result.data || []
      } catch (error) {
        console.error('加载用户列表失败:', error)
      }
    },
    
    // 加载部门列表
    async loadDepartments() {
      try {
        const res = await uniCloud.database().collection('mydb-department').field('name').get()
        this.deptOptions = res.result.data || []
      } catch (error) {
        console.error('加载部门列表失败:', error)
      }
    },
    
    // 筛选条件变更处理
    onTimeTypeChange(e) {
      this.filterForm.timeType = ['day', 'week', 'month', 'year'][e.detail.value]
      this.timeTypeIndex = e.detail.value
    },
    
    onStartDateChange(e) {
      this.filterForm.startDate = e.detail.value
    },
    
    onEndDateChange(e) {
      this.filterForm.endDate = e.detail.value
    },
    
    onDimensionChange(e) {
      this.filterForm.dimension = ['personal', 'department', 'multi-department'][e.detail.value]
      this.dimensionIndex = e.detail.value
    },
    
    onUserChange(e) {
      const user = this.userOptions[e.detail.value]
      this.filterForm.userId = user.id || ''
      this.userIndex = e.detail.value
    },
    
    onDeptChange(e) {
      const dept = this.deptOptions[e.detail.value]
      this.filterForm.deptId = dept.id || ''
      this.deptIndex = e.detail.value
    },
    
    // 多部门选择
    toggleDept(deptId) {
      const index = this.filterForm.multiDepts.indexOf(deptId)
      if (index > -1) {
        this.filterForm.multiDepts.splice(index, 1)
      } else {
        this.filterForm.multiDepts.push(deptId)
      }
    },
    
    getMultiDeptText() {
      if (this.filterForm.multiDepts.length === 0) return '请选择部门'
      const selectedDepts = this.deptOptions.filter(dept => 
        this.filterForm.multiDepts.includes(dept.id)
      )
      return selectedDepts.map(dept => dept.name).join('、')
    },
    
    // 查询统计
    async handleQuery() {
      this.loading = true
      try {
        await Promise.all([
          this.loadStatistics(),
          this.loadTableData(),
		  this.loadChartData() // 新增图表数据加载
        ])
      } catch (error) {
        console.error('查询失败:', error)
        uni.showToast({
          title: '查询失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 加载统计数据
    async loadStatistics() {
      try {
        const res = await uniCloud.callFunction({
          name: 'statistics',
          data: {
            action: 'getDealStatistics',
            params: this.filterForm
          }
        })
        this.statistics = res.result.data || {}
      } catch (error) {
        console.error('加载统计数据失败:', error)
      }
    },
    
    // 加载表格数据
    async loadTableData() {
      try {
        const res = await uniCloud.callFunction({
          name: 'statistics',
          data: {
            action: 'getDealList',
            params: {
              ...this.filterForm,
              page: this.currentPage,
              pageSize: this.pageSize
            }
          }
        })
        this.tableData = res.result.data.data || []
		this.exportExcelData = res.result.data.data || []
        this.total = res.result.data.total || 0
      } catch (error) {
        console.error('加载表格数据失败:', error)
      }
    },
    // 在 methods 中添加以下方法
    
    // 加载图表数据
    async loadChartData() {
      try {
        const res = await uniCloud.callFunction({
          name: 'statistics',
          data: {
            action: 'getChartData',
            params: {
              ...this.filterForm,
              chartType: this.activeChart
            }
          }
        })
        
        const chartData = res.result.data
      
      } catch (error) {
        console.error('加载图表数据失败:', error)
      }
    },
    // 分页处理
    handlePrevPage() {
      if (this.currentPage > 1) {
        this.currentPage--
        this.loadTableData()
      }
    },
    
    handleNextPage() {
      if (this.currentPage * this.pageSize < this.total) {
        this.currentPage++
        this.loadTableData()
      }
    },
    
    // 导出Excel
    async handleExport() {
      uni.showLoading({ title: '导出中...' })
      try {
        const res = await uniCloud.callFunction({
          name: 'statistics',
          data: {
            action: 'exportDealData',
            params: this.filterForm
          }
        })
        
        // 下载文件
        uni.downloadFile({
          url: res.result.fileUrl,
          success: (downloadRes) => {
            if (downloadRes.statusCode === 200) {
              uni.saveFile({
                tempFilePath: downloadRes.tempFilePath,
                success: (saveRes) => {
                  uni.showToast({
                    title: '导出成功',
                    icon: 'success'
                  })
                }
              })
            }
          }
        })
      } catch (error) {
        console.error('导出失败:', error)
        uni.showToast({
          title: '导出失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 工具函数
    formatDate(date) {
      return new Date(date).toLocaleDateString()
    },

  }
}
</script>

<style scoped>
.statistics-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 筛选区域样式 */
.filter-section {
  background: white;
  padding: 30rpx;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20rpx;
  gap: 20rpx;
}

.filter-item {
  flex: 1;
  min-width: 200rpx;
}

.filter-label {
  display: block;
  font-size: 26rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.picker {
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.multi-picker {
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  min-height: 40rpx;
}

.query-btn {
  background: #007AFF;
  color: white;
  border: none;
  border-radius: 8rpx;
  padding: 6rpx;
  font-size: 28rpx;
}

/* 概览区域样式 */
.overview-section {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.overview-card {
  flex: 1;
  min-width: 150rpx;
  background: white;
  padding: 30rpx;
  border-radius: 10rpx;
  text-align: center;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.overview-value {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: #007AFF;
  margin-bottom: 10rpx;
}

.overview-label {
  font-size: 24rpx;
  color: #666;
}

/* 图表区域样式 */
.chart-section {
  background: white;
  padding: 30rpx;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
}

.chart-tabs {
  display: flex;
  border-bottom: 1rpx solid #eee;
  margin-bottom: 30rpx;
}

.chart-tab {
  flex: 1;
  text-align: center;
  padding: 20rpx;
  font-size: 28rpx;
  color: #666;
  border-bottom: 4rpx solid transparent;
}

.chart-tab.active {
  color: #007AFF;
  border-bottom-color: #007AFF;
}

.chart-container {
  padding: 48px 0;
  height: 500rpx;
  background: #f9f9f9;
  border-radius: 8rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.chart-placeholder {
  text-align: center;
}

.chart-tip {
  color: #999;
  font-size: 28rpx;
}

/* 表格区域样式 */
.table-section {
  background: white;
  padding: 30rpx;
  border-radius: 10rpx;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.table-title {
  font-size: 32rpx;
  font-weight: bold;
}

.export-btn {
  color: #007AFF;
  font-size: 26rpx;
}

.table-container {
  width: 100%;
  margin-bottom: 20rpx;
}

.table {
  min-width: 1200rpx;
}

.table-row {
  display: flex;
  border-bottom: 1rpx solid #eee;
}

.table-row.header-row {
  background: #f5f5f5;
  font-weight: bold;
}

.table-cell {
  flex: 1;
  min-width: 150rpx;
  padding: 20rpx 10rpx;
  font-size: 26rpx;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20rpx;
  border-top: 1rpx solid #eee;
}

.pagination-text {
  font-size: 26rpx;
  color: #666;
}

.pagination-btns {
  display: flex;
  gap: 20rpx;
}

.page-btn {
  padding: 10rpx 20rpx;
  font-size: 26rpx;
  border: 1rpx solid #ddd;
  background: white;
  border-radius: 6rpx;
}

.page-btn:disabled {
  color: #ccc;
  background: #f5f5f5;
}

/* 弹窗样式 */
.popup-content {
  background: white;
  border-radius: 20rpx 20rpx 0 0;
  padding: 40rpx;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
}

.popup-close {
  color: #007AFF;
  font-size: 28rpx;
}

.popup-list {
  max-height: 600rpx;
}

.popup-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.dept-name {
  margin-left: 20rpx;
  font-size: 28rpx;
}
</style>